//
//  DataManager.m
//  YiShi
//
//  Created by  zyn on 15/1/4.
//  Copyright (c) 2015年 maochengfang. All rights reserved.
//

#import "DataManager.h"
#import <CommonCrypto/CommonDigest.h>
//#import "UserModel.h"
@implementation DataManager

static DataManager *instance = nil;

+ (DataManager *)newInstance
{
    @synchronized(self)
    {
        if(nil == instance)
        {
            instance = [DataManager new];
        }
    }
    return instance;
}

-(NSString *)getStringDate:(NSDate *)date dateType:(NSString *)type
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:type];      //设置你需要的时间格式
    return [dateFormatter stringFromDate:date];  //格式化date为字符串
}

-(NSDate *)getCurrentDate
{
    // 获取系统当前时间
    NSDate * date = [NSDate date];
    NSTimeInterval sec = [date timeIntervalSinceNow];
    return [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
}

-(void)saveCache:(NSString *)key value:(NSString *)value
{
    if ([value isKindOfClass:[NSNull class]]) {
        value=@"";
    }
    NSUserDefaults *cache = [NSUserDefaults standardUserDefaults];
    [cache setObject:value forKey:key];
    [cache synchronize];
}

-(void)saveBoolCache:(NSString *)key value:(BOOL)value
{
    NSUserDefaults *cache = [NSUserDefaults standardUserDefaults];
    [cache setBool:value forKey:key];
    [cache synchronize];
}

-(BOOL)readBoolCache:(NSString *)key
{
    NSUserDefaults *cache = [NSUserDefaults standardUserDefaults];
    return [cache boolForKey:key];
}

-(NSString *)readCache:(NSString *)key
{
    NSUserDefaults *cache = [NSUserDefaults standardUserDefaults];
    return [cache objectForKey:key];
}

-(void)removeCache:(NSString *)key
{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:key];
    [defaults synchronize];
}

-(void)clearCache
{
    NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
    [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
}

-(Boolean)checkCache:(NSString *)key
{
    NSString *value = [self readCache:key];
    if (value)
    {
        return true;
    }
    return false;
}
//-(UserModel*)getAccountInfo{
    
//    activity = 0;
//    customercode = vjNf52866878;
//    customername = "<null>";
//    id = 88491;
//    mobile = 18352866878;
//    myCollection = 0;
//    myComment = 0;
//    myMessage = 0;
//    myWallet = 0;
//    photo = "<null>";
//    token = "b32a18bd-89c3-43e6-b8c9-c27ffd949735";
    
    
    
//    UserModel *user=[[UserModel alloc]init];
//    user.activity=[[NSUserDefaults standardUserDefaults]objectForKey:@"activity"];
//    user.customercode=[[NSUserDefaults standardUserDefaults]objectForKey:@"customercode"];
//    user.customername=[[NSUserDefaults standardUserDefaults]objectForKey:@"customername"];
//    user.ID=[[NSUserDefaults standardUserDefaults]objectForKey:@"ID"];
//    user.mobile=[[NSUserDefaults standardUserDefaults]objectForKey:@"mobile"];
//    user.myCollection=[[NSUserDefaults standardUserDefaults]objectForKey:@"myCollection"];
//    user.myComment=[[NSUserDefaults standardUserDefaults]objectForKey:@"myComment"];
//    user.myMessage=[[NSUserDefaults standardUserDefaults]objectForKey:@"myMessage"];
//    user.myWallet=[[NSUserDefaults standardUserDefaults]objectForKey:@"myWallet"];
//    user.photo=[[NSUserDefaults standardUserDefaults]objectForKey:@"photo"];
//    user.token=[[NSUserDefaults standardUserDefaults]objectForKey:@"token"];

    
    
//    return user;
//}
-(void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}

-(void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}

-(DataManager *)init:(UIView *)view
{
    if (progress == nil) {
        progress = [MBProgressHUD showHUDAddedTo:view animated:YES];
    }
    return instance;
}

-(void)showProgress:(NSString *)message
{
    progress.labelText = message;
    [progress show:YES];
}
-(void)showProgress
{
    [progress show:YES];
}

-(void)hideProgress
{
    [progress hide:YES];
}

//-(void)createTable
//{
//    NSFileManager * fileManager = [NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:DB_NAME] == NO) {
//        // create it
//        FMDatabase * db = [FMDatabase databaseWithPath:DB_NAME];
//        if ([db open]) {
//            NSString * sql = @"CREATE TABLE 'history' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'bookid' VARCHAR(30), 'name' VARCHAR(30), 'intro' VARCHAR(30), 'author' VARCHAR(30), 'image' VARCHAR(30))";
//            BOOL res = [db executeUpdate:sql];
//            if (!res) {
//                debugLog(@"error when creating db table");
//            } else {
//                debugLog(@"succ to creating db table");
//            }
//            [db close];
//        } else {
//            debugLog(@"error when open db");
//        }
//    }
//}
//
//-(void)insertDBData:(Model *)model
//{
//    if ([self queryDBData].count >9) {
//        // 当前记录到达了10条
//        NSString *bookId = ((BookModel*)[self queryDBData][0]).book_id;
//        [self deleteDBById:bookId];
//    }
//    
//    BookModel *book = (BookModel *)model;
//    FMDatabase * db = [FMDatabase databaseWithPath:DB_NAME];
//    if ([db open]) {
//        
//        NSString * sql = @"insert into history (bookid, name, intro, author, image) values(?, ?, ?, ?, ?) ";
//        FMResultSet *rs = [db executeQuery:@"select * from history where bookid = ?",book.book_id];
//        BOOL res;
//        if ([rs next]) {
//            // 数据库中已经存在该条记录,所以进行更新操作
//            NSString *updateSql = [NSString stringWithFormat:@"update history set name = ?,intro = ?,author = ?,image = ? where bookid = %@",book.book_id];
//            res = [db executeUpdate:updateSql,book.name,book.digest,book.author,book.image];
//        }else{
//            res = [db executeUpdate:sql, book.book_id, book.name,book.digest,book.author,book.image];
//        }
//        if (!res) {
//            debugLog(@"error to insert data");
//        } else {
//            debugLog(@"succ to insert data");
//        }
//        [db close];
//    }
//
//}
//
//-(NSArray *)queryDBData
//{
//    FMDatabase * db = [FMDatabase databaseWithPath:DB_NAME];
//    if ([db open]) {
//        NSMutableArray *arr = [[NSMutableArray alloc]initWithCapacity:0];
//        NSString * sql = @"select * from history";
//        FMResultSet * rs = [db executeQuery:sql];
//        while ([rs next]) {
//            
//            BookModel *book = [[BookModel alloc]init];
//            book.book_id = [rs stringForColumn:@"bookid"];
//            book.name = [rs stringForColumn:@"name"];
//            book.digest = [rs stringForColumn:@"intro"];
//            book.author = [rs stringForColumn:@"author"];
//            book.image = [rs stringForColumn:@"image"];
//
//            [arr addObject:book];
//        }
//        [db close];
//        return arr;
//    }else{
//        return nil;
//    }
//        
//}
//
//-(void)deleteDBById:(NSString *)ID
//{
//    FMDatabase * db = [FMDatabase databaseWithPath:DB_NAME];
//    if ([db open]) {
//        [db setShouldCacheStatements:YES];
//        BOOL result = [db executeUpdate:@"delete from history where bookid = ?",ID];
//        if (result) {
//            debugLog(@"succ to delete by id");
//        }else{
//            debugLog(@"error to delete by id");
//        }
//        [db close];
//    }
//}
//
//-(void)clearDBData
//{
//    FMDatabase * db = [FMDatabase databaseWithPath:DB_NAME];
//    if ([db open]) {
//        NSString * sql = @"delete from history";
//        BOOL res = [db executeUpdate:sql];
//        if (!res) {
//            debugLog(@"error to delete db data");
//        } else {
//            debugLog(@"succ to deleta db data");
//        }
//        [db close];
//    }
//
//}

-(NSString *)imageToBase64:(UIImage *)image
{
    NSData *_data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *_encodedImageStr = [_data base64Encoding];
    return _encodedImageStr;
}

-(UIImage *)base64ToImage:(NSString *)base64
{
    NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:base64];
    UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
    return _decodedImage;
}

-(NSString *)intToString:(NSInteger) value
{
    return [NSString stringWithFormat:@"%ld",(long)value];
}

/** 登录过期处理 */
//-(void)againLogin:(UIViewController *)controller state:(NSString *)stateCode
//{
//    if (![stateCode isEqualToString:TOKEN_INVALID])
//        return;
//    
//    vc = controller;
//    UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"通知" message:@"抱歉！您的登录已经过期，点击重新登录。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
//    [view show];
//    
//}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex != alertView.cancelButtonIndex) {
//        NSString *username = USER_NAME;
//        [self clearCache];
//        [self saveCache:@"username" value:username];
//        [vc.navigationController.navigationController popToRootViewControllerAnimated:YES];
//    }
//}

-(UIImage *)urlToUIImage:(NSString *)url;
{
    NSURL*nsurl=[NSURL URLWithString:[@"URL_FILE_IMAGE" stringByAppendingString:url]];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:nsurl]];
    return image;
}

-(NSString *)urlEncodedString:(NSString *)url{
    return [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


-(NSDate *)stringToDate:(NSString *)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    return [dateFormatter dateFromString:dateString];
}

-(UIColor *)rgba:(NSInteger)red green:(NSInteger) green blue:(NSInteger)blue{
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
}

-(UIColor *)rgba_16:(NSString *)colorString{
    NSInteger red = strtoul([[colorString substringWithRange:NSMakeRange(0, 2)] UTF8String],0,16);
    NSInteger green = strtoul([[colorString substringWithRange:NSMakeRange(2, 2)] UTF8String],0,16);
    NSInteger blue = strtoul([[colorString substringWithRange:NSMakeRange(4, 2)] UTF8String],0,16);
    
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
}

-(void)setShadow:(UIView *)view{
    //添加四个边阴影
    view.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
    view.layer.shadowOffset = CGSizeMake(2,2);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    view.layer.shadowOpacity = 0.5;//阴影透明度，默认0
    view.layer.shadowRadius = 1.5;//阴影半径，默认3

}

-(NSString *)toString:(id)value{
    if ([value isKindOfClass:[NSString class]])
        return value;
    return [NSString stringWithFormat:@"%@",value];
    
}

-(void)resetEdgeAntialiase:(UIView *)view{
    view.layer.allowsEdgeAntialiasing = YES;
}


#pragma mark - 修改界面圆角及灰边
- (void)setRadius:(UIView *)view withCornerRadius:(CGFloat)cornerRadius BorderWidth:(CGFloat)BorderWidth andBorderColor:(CGColorRef)BorderColor
{
    CALayer *layer = [view layer];
    [layer setMasksToBounds:YES];
    [layer setCornerRadius:cornerRadius];
    [layer setBorderWidth:BorderWidth];
    [layer setBorderColor:BorderColor];
}
- (void)setBtnRadius:(UIView *)view{
    CALayer *layer = [view layer];
    [layer setMasksToBounds:YES];
    [layer setCornerRadius:(view.frame.size.height/2)];
}

/** 弹出框动画 */
#pragma mark 关键帧动画
-(void)translationAnimation:(UIView *)view{
    
    CAKeyframeAnimation *orbit = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    //2.设置关键帧,这里有四个关键帧
    CATransform3D scale1 = CATransform3DMakeScale(0.0, 0.0, 1);
    CATransform3D scale2 = CATransform3DMakeScale(1.1, 1.1, 1);
    CATransform3D scale3 = CATransform3DMakeScale(0.9, 0.9, 1);
    CATransform3D scale4 = CATransform3DMakeScale(1.0, 1.0, 1);
    
    NSValue *key1=[NSValue valueWithCATransform3D:scale1];//对于关键帧动画初始值不能省略
    NSValue *key2=[NSValue valueWithCATransform3D:scale2];
    NSValue *key3=[NSValue valueWithCATransform3D:scale3];
    NSValue *key4=[NSValue valueWithCATransform3D:scale4];
    NSArray *values=@[key1,key2,key3,key4];
    
    orbit.duration = 0.4;
    orbit.values = values;
    orbit.keyTimes = @[@0.0f,@0.6f,@0.8f,@1.0f];
    
    orbit.beginTime = CACurrentMediaTime();
    [view.layer addAnimation:orbit forKey:@"orbit"];
    
}

#pragma mark - 取消弹框
-(void)closeAnimation:(UIView *)view delegate:(id)delegate{
    CAKeyframeAnimation *orbit = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    //2.设置关键帧,这里有四个关键帧
    CATransform3D scale1 = CATransform3DMakeScale(1.0, 1.0, 1);
    CATransform3D scale2 = CATransform3DMakeScale(0.9, 0.9, 1);
    CATransform3D scale3 = CATransform3DMakeScale(1.1, 1.1, 1);
    CATransform3D scale4 = CATransform3DMakeScale(0.0, 0.0, 1);
    
    NSValue *key1=[NSValue valueWithCATransform3D:scale1];//对于关键帧动画初始值不能省略
    NSValue *key2=[NSValue valueWithCATransform3D:scale2];
    NSValue *key3=[NSValue valueWithCATransform3D:scale3];
    NSValue *key4=[NSValue valueWithCATransform3D:scale4];
    NSArray *values=@[key1,key2,key3,key4];
    //    NSArray *values=@[key1,key2,key3];
    
    orbit.duration = 0.6;
    orbit.values = values;
    orbit.delegate = delegate;
    orbit.keyTimes = @[@0.0f,@0.2f,@0.6f,@1.0f];
    orbit.fillMode = kCAFillModeForwards;
    orbit.removedOnCompletion = NO;
    //    orbit.keyTimes = @[@0.0f,@0.2f,@1.0f];
    
    orbit.beginTime = CACurrentMediaTime();
    [view.layer addAnimation:orbit forKey:@"orbit"];
}
@end
